package org.example.fronted.utils.utils;


import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.text.RandomStringGenerator;
import org.apache.http.HttpResponse;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage;

/****
 * 扫码支付
 * @author admin
 *
 */
public class WeixinPay {


    private static final int BLACK = 0xff000000;
    private static final int WHITE = 0xFFFFFFFF;


    public static String getCodeUrl(WeChatParams ps) throws IOException {

//        try {
//            /**
//             * 账号信息
//             */
////            String appid = WeChatConfig.APPID;//微信服务号的appid
////            String mch_id = WeChatConfig.MCHID; //微信支付商户号
////            String key = WeChatConfig.APIKEY; // 微信支付的API密钥
////            String notify_url = WeChatConfig.WECHAT_NOTIFY_URL_PC;//回调地址【注意，这里必须要使用外网的地址】
////            String ufdoder_url=WeChatConfig.UFDODER_URL;//微信下单API地址
//            String appid = "wx632c8f211f8122c6";//微信服务号的appid
//            String mch_id = "1497984412"; //微信支付商户号
//            String key = "sbNCm1JnevqI36LrEaxFwcaT0hkGxFnC"; // 微信支付的API密钥
//            String notify_url = "http://hello.free.idcfengye.com/index.jsp";//回调地址【注意，这里必须要使用外网的地址】
//            String ufdoder_url= "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信下单API地址
//            String trade_type = "NATIVE"; //类型【网页扫码支付】
//
//            /**
//             * 时间字符串
//             */
//            String currTime = PayForUtil.getCurrTime();
//            String strTime = currTime.substring(8, currTime.length());
//            String strRandom = PayForUtil.buildRandom(4) + "";
//            String nonce_str = strTime + strRandom;
//            TreeMap<String,Object> packageParams = new TreeMap<String,Object>();
//            packageParams.put("appid", appid);
//            packageParams.put("mch_id", mch_id);
//            packageParams.put("nonce_str", nonce_str);//随机字符串
//            packageParams.put("body", ps.body);//支付的商品名称
//            packageParams.put("out_trade_no", ps.out_trade_no+nonce_str);//商户订单号【备注：每次发起请求都需要随机的字符串，否则失败。】
//            packageParams.put("total_fee", ps.total_fee);//支付金额
//            packageParams.put("spbill_create_ip", PayForUtil.localIp());//客户端主机
//            packageParams.put("notify_url", notify_url);
//            packageParams.put("trade_type", trade_type);
//            packageParams.put("attach", ps.attach);//额外的参数【业务类型+会员ID+支付类型】
//            String sign = PayForUtil.createSign("UTF-8", packageParams,key);  //获取签名
//            packageParams.put("sign", sign);
//
//            String requestXML = XMLUtilTest.createXML(packageParams);
//            System.err.println("微信支付请求参数的报文"+requestXML);
//
////            String requestXML = PayForUtil.getRequestXml(packageParams);//将请求参数转换成String类型
////            InputStream is = new FileInputStream(ufdoder_url);
////
////            String elementValue = XMLUtilTest.getElementValue(is, key);
//            HttpResponse response = XMLUtilTest.sendXmlDataByPost(ufdoder_url, requestXML);
//
//
//            String code_url = XMLUtilTest.getElementValue(inputStream, "code_url"); //获取二维码地址
//
//            //生成二维码图片
//            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
//            Map hints = new HashMap();
//            BitMatrix bitMatrix = null;
//            try {
//                bitMatrix = multiFormatWriter.encode(code_url, BarcodeFormat.QR_CODE, 250, 250, hints);
//                BufferedImage image = toBufferedImage(bitMatrix);
//                ImageIO.write(image,"png", response.getOutputStream());
//            } catch (WriterException e) {
//                e.printStackTrace();
//            }
//
////            String resXml = HttpUtil.postData(ufdoder_url,requestXML);  //解析请求之后的xml参数并且转换成String类型
//
////            Map map = XMLUtil.doXMLParse(resXml);
////            String urlCode = (String) map.get("code_url");
////            System.err.println("微信支付响应参数的报文"+resXml);
////            System.err.println("返回的地址 ===================");
////            System.err.println(urlCode);
////            return urlCode;
////        } catch (Exception e) {
////            // TODO: handle exception
////            e.printStackTrace();
////        }
//        return null;
        return null;
    }








    /**
     * 将路径生成二维码图片
     * @author chenp
     * @param content
     * @param response
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static String encodeQrcode(String content,HttpServletResponse response) throws IOException, WriterException {

        String filePath = "D:/Program File/nigix-server/nginx-1.17.2/html";
        String fileName = ".png";

        RandomStringGenerator generator = new RandomStringGenerator.Builder()
                .withinRange(new char[]{'a', 'z'}, new char[]{'A', 'Z'}, new char[]{'0', '9'}).build();

//        String newFileName = System.nanoTime() + generator.generate(10) + fileNameSuffix;
        String newFileName=generator.generate(10)+fileName;

        JSONObject json = new JSONObject();
        json.put("content",content);
//        json.put(
//                "zxing",
//                "https://github.com/zxing/zxing/tree/zxing-3.0.0/javase/src/main/java/com/google/zxing");
//        json.put("author", "shihy");

        content = json.toJSONString();// 内容
        int width = 200; // 图像宽度
        int height = 200; // 图像高度
        String format = "png";// 图像类型

        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
        Path path = FileSystems.getDefault().getPath(filePath, newFileName);
        MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
        // 随机字符串生成器
        System.out.println("输出成功.");
        return newFileName;



    }
    /**
     * 类型转换
     * @author chenp
     * @param matrix
     * @return
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
            }
        }
        return image;
    }
    // 特殊字符处理
    public static String UrlEncode(String src)  throws UnsupportedEncodingException {
        return URLEncoder.encode(src, "UTF-8").replace("+", "%20");
    }


}
